package com.aco.party.web.controller.system;

import com.aco.party.model.po.Message;
import com.aco.party.model.po.User;
import com.aco.party.model.vo.MessageParam;
import com.aco.party.model.vo.MessageVo;
import com.aco.party.model.vo.UserQueryParam;
import com.aco.party.model.vo.common.DataGridEntry;
import com.aco.party.model.vo.common.Page;
import com.aco.party.model.vo.common.PageParam;
import com.aco.party.model.vo.common.Response;
import com.aco.party.service.system.MessageService;
import com.aco.party.service.system.MetaService;
import com.aco.party.service.system.RoleService;
import com.aco.party.service.system.UserService;
import com.aco.party.web.command.system.EditMessageCommand;
import com.aco.party.web.validator.system.EditMessageValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * Created by flying on 3/10/2016 0010.
 */
@Controller
@RequestMapping("/system")
public class ManageMessageController extends BaseController {
    Logger logger = LoggerFactory.getLogger(ManageMessageController.class);

    @Resource
    private MessageService messageService;

    @Resource
    private MetaService metaService;

    @Resource
    private RoleService roleService;

    @Resource
    private UserService userService;

    private EditMessageValidator validator = new EditMessageValidator();

    private final String REDIRECT = "redirect:sendMessageSuc";

    @RequestMapping(value = {"/message", "/message/list"}, method = RequestMethod.GET)
    public String showManagePage(HttpServletResponse response) {
        return "system/manageMessages";
    }

    @RequestMapping(value = "message/list", method = RequestMethod.POST)
    @ResponseBody
    public Page
            <MessageVo> getListJson(HttpServletRequest request, DataGridEntry entry) {
        Page <MessageVo> page = new Page<>();
        entry.webParamConvert();
        MessageParam param = new MessageParam();
        List <MessageVo> list = messageService.getByPage(new PageParam(entry.getOffset(), entry.getLimit()),param);
        page.setTotal(messageService.getTotal(param));
        page.setRows(list);
        return page;
    }

    @RequestMapping(value = "/message/edit", method = RequestMethod.GET)
    public String showEdit(HttpServletResponse response,@ModelAttribute EditMessageCommand command, Model model) {
        if (command.getId() != null) {
            Message po = messageService.getByPrimaryKey(command.getId());
            if (po != null)
                command.toCommand(po);
            else
                model.addAttribute("no_obj", true);
        }
        return "system/editMessage";
    }

    @RequestMapping(value = "/message/edit", method = RequestMethod.POST)
    public String edit(Model model, @ModelAttribute EditMessageCommand command, BindingResult errors) {
        validator.validate(command, errors);
        setAtt(model);
        if (!errors.hasErrors()) {
            Message message = new Message();
                command.toPo(message);
            message.setUpdateTime(new Date());
            messageService.update(message);
            model.addAttribute("no_error",true);
        }
        return "system/editMessage";
    }

    @RequestMapping(value = "/message/add", method = RequestMethod.GET)
    public String showAdd(Model model,@ModelAttribute EditMessageCommand command) {
        command.setStatus(1);
        setAtt(model);
        return "system/editMessage";
    }

    @RequestMapping(value = "/message/add", method = RequestMethod.POST)
    public String add(Model model, @ModelAttribute EditMessageCommand command, BindingResult errors,RedirectAttributes attributes) {
        validator.validate(command, errors);
        if (errors.hasErrors()) {
            setAtt(model);
            return "system/editMessage";
        }
        Message message;
        List<User> users;
        if(command.getSelectRoleId() != 0) {
            UserQueryParam queryParam = new UserQueryParam();
            queryParam.setRoleId(command.getSelectRoleId().intValue());
            users = userService.getUsersByParam(queryParam);
        }else {
            users = userService.getAllUsers();
        }
        
        if(users != null){
            for (User user: users){
                message = new Message();
                command.toPo(message);
                message.setTarget(user.getId());
                message.setCreator(getCurrentUser().getId());
                message.setCreateTime(new Date());
                messageService.add(message);
            }
        }

        attributes.addFlashAttribute("no_error", true);
         return REDIRECT;
    }

    @RequestMapping(value = "/message/delete",method = RequestMethod.POST)
    @ResponseBody
    public Response del(@RequestParam(required = true) Long id){
        logger.info("删除：" + id);
        messageService.delete(id);
        return new Response();
    }

    private void setAtt(Model model){
        model.addAttribute("roles", roleService.findAllRoles());
    }

    @RequestMapping(value = "/message/sendMessageSuc")
    public String sendMessageSuc(Model model){
        model.addAttribute("msg","<strong>Well done! </strong>发送成功！");
        model.addAttribute("url","/system/message/list");
        return "system/messageSuc";
    }

}
